<template>
  <el-dialog v-model="dialogVisible" title="文件上传" width="30%" @close="cancelFn">
    <el-form ref="ruleFormRef" :model="submitData" :rules="rules" class="file-upload-form" label-width="120px" status-icon
      style="width: 90%">
      <el-form-item label="业务" prop="bizId">
        <el-select v-model="submitData.bizId" placeholder="业务" style="width: 100%" @change="selectBizChange">
          <el-option v-for="item in bizOptions" :key="item.bizId" :label="item.bizName" :value="item.bizId" />
        </el-select>
      </el-form-item>
      <el-form-item label="子业务" prop="">
        <el-select v-model="submitData.subBizId" placeholder="子业务" style="width: 100%">
          <el-option v-for="item in subBizOptions" :key="item.subBizId" :label="item.subBizName" :value="item.subBizId" />
        </el-select>
      </el-form-item>
      <el-form-item label="文件描述" prop="description">
        <el-input v-model="submitData.description" type="textarea" />
      </el-form-item>
      <el-form-item label="文件上传" prop="file">
        <el-upload ref="uploadRef" class="upload-cdn-file" action="#" :limit="1" :auto-upload="false" drag :on-change="handleChange" :on-remove="handleRemove">
          <div class="el-upload__text">
            拖拽文件或点击上传
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirmFn(ruleFormRef)">提交</el-button>
        <el-button @click="cancelFn">取消</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>
</template>

<script  setup>
import { reactive, ref,toRaw, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { querySubBizList, uploadCdnFile } from '@/api/fileListApi.js';

const props = defineProps(['bizOptions'])
const emit = defineEmits(['feedbackFn'])
const ruleFormRef = ref(null);
const uploadRef = ref(null);
const dialogVisible = ref(false);
const subBizOptions = ref([])
// 表单
let submitData = reactive({
  bizId: '',
  subBizId: '',
  description: '',
  file: null
})
const rules = reactive({
  bizId: [{ required: true, message: '请选择业务名称', trigger: 'change' }],
  subBizId: [{ required: true, message: '请选择子业务', trigger: 'change' }],
  file: [{ required: true, message: '请上传文件',trigger:'change'}],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
})
// 根据bizId 获取subBIz list
const selectBizChange = (bizId) => {
  getSubBizList(bizId)
}
// 弹窗打开时，清除表单校验
const switchVisible = () => {
  dialogVisible.value = true;
  nextTick(()=> {
    ruleFormRef.value.clearValidate()
    // 若上传文件夹 则打开下面的注释
    // document.getElementsByClassName("el-upload__input")[0].webkitdirectory = true; //布尔值，true: 选择文件夹，false: 选中文件
  });
  
}
// 查询子业务的下拉选项
const getSubBizList = (bizId) => {
  querySubBizList(bizId).then((res) => {
    if (res.data.code === 200) {
      let response = res.data.data;
      subBizOptions.value = response;
    }
  })
};

// 选择文件时被调用，将其赋值给submitData.file，并清除对file的校验
const handleChange = (file) => {
  submitData.file = file
  ruleFormRef.value.clearValidate('file')
}
// 移除上传的文件
const handleRemove = (file) => {
  submitData.file = null
}
//取消 、关闭弹窗
const cancelFn = () => {
  dialogVisible.value = false
  // 表单初始化
  submitData.bizId = '';
  submitData.subBizId = '';
  submitData.description = '';
  submitData.file = null;
  // 上传文件清除
  uploadRef.value.clearFiles()
  subBizOptions.value = []

}
// 确定上传
const confirmFn = (formEl) => {
  let req = toRaw(submitData)
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      submitFn(req)
    } else {
      return false
    }
  })

}
// 向后端发起请求，提交form数据和file文件
const submitFn = async (req) => {
  let createBy = '';
  try {
    createBy = JSON.parse(localStorage.getItem('userInfo')).employeeId;
  } catch (e) {
  }
  let param = new FormData()
  // 将file和表单字段append到param里，传给后端 
  param.append("file", req.file.raw)
  param.append("bizId", req.bizId)
  param.append("subBizId", req.subBizId)
  param.append("description", req.description)
  param.append("createBy", createBy)
  // 发个后端
  const res = await uploadCdnFile(param)
  if (res.data.code === 200) {
    ElMessage({
      message: '上传成功',
      type: 'success'
    })
  } else {
    ElMessage({
      message: '上传失败',
      type: 'error'
    })
  }
  cancelFn()
  emit('feedbackFn')
}
defineExpose({
  switchVisible
})

</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

.upload-cdn-file::v-deep .el-upload {
  width:100%;
}
::v-deep .el-upload-list__item-name{
    white-space: normal !important;
  }
.upload-cdn-file::v-deep .el-upload-dragger {
  display: flex;
  justify-content: center !important;
  align-items: center !important;
  width: 100%;
}
</style>